﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace DataLib
{
    /// <summary>
    /// 目的：引用类型深拷贝
    /// </summary>
    public class Memento
    {
        /// <summary>
        /// 暂存：属性——值
        /// </summary>
        private Dictionary<PropertyInfo, object> _storedProps = new Dictionary<PropertyInfo, object>();

        /// <summary>
        /// 将 obj 的值存入 _storedProps
        /// </summary>
        /// <param name="obj"></param>
        public void StoreObjectProps(object obj)
        {
            var props = (obj.GetType()).GetProperties
                (BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite); 
            foreach (var property in props)
            {
                try
                {
                    _storedProps[property] = property.GetValue(obj, null);
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                }
            }
        }

        /// <summary>
        /// 将 _storedProps 的值恢复至（还原作用） obj
        /// </summary>
        /// <param name="obj">必须已初始化，不能为 null</param>
        public void RetrieveObjectProps(object obj)
        {
            foreach (var pair in _storedProps)
            {
                try
                {
                    pair.Key.SetValue(obj, pair.Value, null);
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                }
            }
        }
    }
}
